class Record {
  constructor() {
    this.url =
      "https://csgomax.oss-cn-shenzhen.aliyuncs.com/csgomax/open_music.mp3";
    this.isChrome =
      /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    this.record = null;
  }
  playMp3() {
    if (!this.isChrome) {
      this.record = new Audio(this.url);
      this.record.src = this.url;
      this.record.currentTime = 0;
      this.record.play();
      console.log("进来2");
    } else {
      try {
        this.playAudio(this.url);
      } catch (e) {
        console.log("!Your browser does not support AudioContext");
      }
    }
  }
  play(context, decodeBuffer) {
    // 调用resume恢复播放
    context.resume();
    // this.context=context
    this.record = context.createBufferSource();
    this.record.buffer = decodeBuffer;
    this.record.connect(context.destination);
    this.record.start(0);
  }
  async playAudio(url) {
    let audioMedia = await this.request(url);
    const context = new (window.AudioContext || window.webkitAudioContext)();
    context.decodeAudioData(audioMedia, decode => this.play(context, decode));
  }
  request(url) {
    return new Promise(resolve => {
      let xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      // 这里需要设置xhr response的格式为arraybuffer
      // 否则默认是二进制的文本格式
      xhr.responseType = "arraybuffer";
      xhr.onreadystatechange = function() {
        // 请求完成，并且成功
        if (xhr.readyState === 4 && xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }
  stopMp3() {
    if (!this.isChrome) {
        this.record.pause();
    }else{
      this.record.stop();
    }
  }
}

export default Record;
